#include <functional>
#include <iostream>

/*
std::function的实现原理
*/
void foo(std::string str) {
    std::cout << str << std::endl;
}

int sum(int a, int b) {
    return a + b;
}

// 自定义实现std::function
template <typename FTY>
class MyFunction {};

#if 0
template <typename R, typename A1>
class MyFunction<R(A1)> {
public:
    using PFUNC = R (*)(A1);
    MyFunction(PFUNC pfunc) : _func(pfunc) {
    }

    R operator()(A1 arg) {
        return _func(arg);
    }

private:
    PFUNC _func;
};

template <typename R, typename A1, typename A2>
class MyFunction<R(A1, A2)> {
public:
    using PFUNC = R (*)(A1, A2);
    MyFunction(PFUNC pfunc) : _func(pfunc) {
    }

    R operator()(A1 arg, A2 arg2) {
        return _func(arg, arg2);
    }

private:
    PFUNC _func;
};
#endif

template <typename R, typename... A>
class MyFunction<R(A...)> {
public:
    using PFUNC = R (*)(A...);
    MyFunction(PFUNC func) : _func(func) {
    }

    R operator()(A... args) {
        return _func(args...);
    }

private:
    PFUNC _func;
};
int main() {
    std::function<void(std::string)> func1 = foo;
    func1("hello, std::function");

    // 使用自定义实现MyFunction
    MyFunction<void(std::string)> func2 = foo;
    func2("hello, MyFunction");

    MyFunction<int(int, int)> func3 = sum;
    std::cout << func3(1, 2) << std::endl;
    return 0;
}
